package org.aman.publish.util;

import com.jcraft.jsch.ChannelExec;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @author DaiJG
 * @title RunThread功能描述
 * @Date created at 2019/8/30 11:30
 * @Description
 * @since 1.0.0
 */
public class SshExecRespThread extends Thread{
    ChannelExec channelExec;
    String printType;
    List<String> result;
    
    public static final String INFO = "INFO";
    public static final String ERROR = "ERROR";
    
    SshExecRespThread(ChannelExec channelExec, String printType, List<String> result) {
        this.channelExec = channelExec;
        this.printType = printType;
        this.result = result;
    }

    public void run() {
        try {
            byte[] tmp = new byte[1024];
            InputStream in = INFO.equals(printType) ? channelExec.getInputStream() : channelExec.getErrStream();
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
                    String line = new String(tmp, 0, i);
                    if(INFO.equals(printType)){
                        System.out.print("info:" + line);
                    } else {
                        System.err.print("err:" + line);
                    }
                    if(result != null){
                        result.add(printType + " > " + line);
                    }
                }
                if (channelExec.isClosed()) {
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception ee) {
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}
